package cn.com.aiouyi.plugin.localStorage;

import cn.com.aiouyi.common.Message;
import cn.com.aiouyi.entity.PluginConfig;
import cn.com.aiouyi.service.PluginConfigService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * Controller - 本地文件存储
 */
@RestController("adminLocalStorageController")
@RequestMapping("/admin/storage_plugin/local_storage")
public class LocalStorageController {

	@Resource(name = "localStoragePlugin")
	private LocalStoragePlugin localStoragePlugin;
	@Resource(name = "pluginConfigServiceImpl")
	private PluginConfigService pluginConfigService;


	/**
	 * 安装
	 */
	@RequestMapping(value = "/install", method = RequestMethod.POST)
	public Message install() {
		if (!localStoragePlugin.getIsInstalled()) {
			PluginConfig pluginConfig = new PluginConfig();
			pluginConfig.setPluginId(localStoragePlugin.getId());
			pluginConfig.setIsEnabled(false);
			pluginConfig.setAttributes(null);
			pluginConfigService.save(pluginConfig);
		}
		return Message.success();
	}

	/**
	 * 卸载
	 */
	@RequestMapping(value = "/uninstall", method = RequestMethod.POST)
	public @ResponseBody
    Message uninstall() {
		if (localStoragePlugin.getIsInstalled()) {
			pluginConfigService.deleteByPluginId(localStoragePlugin.getId());
		}
		return Message.success();
	}


	/**
	 * 设置
	 */
	@GetMapping(value = "/setting")
	public Message setting() {
		PluginConfig pluginConfig = localStoragePlugin.getPluginConfig();
		return Message.successData(pluginConfig);
	}

	/**
	 * 更新
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public Message update(Integer seq, String imageFilePath, String textFilePath, Long maxSize,
                          String imageFileSuffix, String textFileSuffix, RedirectAttributes redirectAttributes) {
		PluginConfig pluginConfig = localStoragePlugin.getPluginConfig();
		Map<String, String> attributes = new HashMap<String, String>();
		attributes.put("imageFilePath", imageFilePath);
		attributes.put("textFilePath", textFilePath);
		attributes.put("maxSize", maxSize.toString());
		attributes.put("imageFileSuffix", imageFileSuffix);
		attributes.put("textFileSuffix", textFileSuffix);
		pluginConfig.setAttributes(attributes);
		pluginConfig.setIsEnabled(true);
		pluginConfig.setSeq(seq);
		pluginConfigService.update(pluginConfig);
		return Message.success();
	}

}